/**
 * File: FastEntryWriter.java
 * Created by: mhaimel
 * Created on: Aug 1, 2011
 * CVS:  $Id: FastEntryWriter.java 1.0 Aug 1, 2011 2:44:14 PM mhaimel Exp $
 */
package uk.ac.ebi.curtain.storage.sequence.fast;

import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

import uk.ac.ebi.curtain.storage.sequence.SequenceBox;

/**
 * @author mhaimel
 * 
 */
public class FastEntryWriter {

	private final PrintWriter out;
	private final char sep;
	private final String nl;
	private final ThreadLocal<StringBuilder> tmp;

	public FastEntryWriter(PrintWriter out, char sep) {
		this(out, sep, System.getProperty("line.separator"));
	}
	public FastEntryWriter(PrintWriter out, char sep, String nl) {
		this.out = out;
		this.sep = sep;
		this.tmp = new ThreadLocal<StringBuilder>();
		this.nl = nl;
	}
	
	public void write(Long id, SequenceBox entry) throws IOException {
		out.print(getString(id, entry));
	}

	public String getString(Long id, SequenceBox entry) throws IOException {
		StringBuilder sb = tmp.get();
		if (null == sb) {
			sb = new StringBuilder();
			tmp.set(sb);
		}
		sb.setLength(0); //reset
		sb.append(id.toString())
			.append(sep)
			.append(entry.getId());
		String[] s = entry.getSequences();
		int i = 0;
		int len = s.length;
		while (i < len) {
			sb.append(sep);
			sb.append(s[i++]);
		}
		sb.append(nl);
		return sb.toString();
	}

	public PrintWriter getWriter() {
		return out;
	}
}
